﻿# ------------------------------------------------- #
# Cloud Service Reserved Virtual IP (VIP) Functions #
# ------------------------------------------------- #

# Add Reserved VIPs
function Add-ReservedIPs([System.Xml.XmlElement]$subscription)
{
	if (!(Should-Run($subscription.reservedIPs))) { return }
	foreach ($reservedIP in $subscription.reservedIPs.reservedIP)
	{
	    if (!(Should-Run($reservedIP))) { continue }
		Write-Information "Adding Reserved VIP '$($reservedIP.name)' ... " -NoNewLine $true
	    if (Get-AzureReservedIP | ? {$_.ReservedIPName -eq $reservedIP.name})
		{
			Write-Text "skipped."
		}
		else
		{
		    $operation = New-AzureReservedIP –ReservedIPName $reservedIP.name –Label $reservedIP.label –Location $reservedIP.location
		    if (!$? -or $operation.OperationStatus -ne "Succeeded") {throw "Reserved VIP '$($reservedIP.name)' operation failed."}
			Write-Text "done."
		}
        Assign-ReservedIPResourceGroup $reservedIP
	}
}

# Remove Reserved VIPs
function Remove-ReservedIPs([System.Xml.XmlElement]$subscription)
{
	if (!(Should-Run($subscription.reservedIPs))) {return}
	foreach ($reservedIP in $subscription.reservedIPs.reservedIP)
	{
	    if (!(Should-Run($reservedIP))) { continue }
	    if (Get-AzureReservedIP | ? {$_.ReservedIPName -eq $reservedIP.name})
		{
		    Write-Information "Removing Reserved VIP '$($reservedIP.name)' ... " -NoNewLine $true
		    $operation = Remove-AzureReservedIP -ReservedIPName $reservedIP.name -Force
		    if (!$? -or $operation.OperationStatus -ne "Succeeded") {throw "Reserved VIP '$($reservedIP.name)' operation failed."}
			Write-Text "done."
		}
		else
		{
		    Write-Information "Removing Reserved VIP '$($reservedIP.name)' ... skipped."
		}
	}
}

# Assign Reserved VIP resource group
function Assign-ReservedIPResourceGroup($reservedIP)
{
    if ($reservedIP.resourceGroup -ne $null)
    {
        Write-Information "Adding Reserved VIP '$($reservedIP.name)' resource group '$($reservedIP.resourceGroup)' ... " -NoNewLine $true
	    if (Move-ResourceItem $reservedIP.name "Microsoft.ClassicNetwork/reservedIps" $reservedIP.resourceGroup)
	    {
		    Write-Text "done."
	    }
	    else
	    {
		    Write-Text "skipped."
	    }
    }
}